import json


from django.contrib.contenttypes.models import ContentType
from apps.comments.models import Comment
from apps.likes.models import LikeCount,LikeRecord
from django.http import JsonResponse
from django.views import View


from utils.models import BaseModel


class change_like(View):
    def get(self,request):
        content_type = request.GET.get('content_type')
        model_class = ContentType.objects.get(model=content_type)
        article_likes =LikeCount.objects.filter(content_type=model_class).order_by('-object_id')
        like_list=[]
        for item in article_likes:
            num=Comment.objects.filter(content_type=model_class,object_id=item.object_id).count()
            like_list.append({
                'id':item.object_id,
                'like_num':item.liked_num,
                'comment_num':num
            })
        return JsonResponse({'code': 0, 'errmsg': '获取点赞数据成功','like_list':like_list})
    def post(self,request):
        data=json.loads(request.body.decode())
        try:
            user=request.user
        except:
            return JsonResponse({'code':400,'errmsg':'用户未登录'})
        content_type=data.get('content_type')
        object_i=data.get('object_id')
        object_id=int(object_i)
        content_type3=ContentType.objects.get(model=content_type)
        like_record,created=LikeRecord.objects.get_or_create(content_type=content_type3,object_id=object_id,user=user)
        if created:
            like_count, created = LikeCount.objects.get_or_create(content_type=content_type3, object_id=object_id)
            like_count.liked_num += 1
            like_count.save()
            return JsonResponse({'code': 0, 'errsmg': '点赞成功'})

        else:
            like_record = LikeRecord.objects.get(content_type=content_type3, object_id=object_id, user=user)
            like_record.delete()
            # 点赞总数减1
            like_count, created = LikeCount.objects.get_or_create(content_type=content_type3, object_id=object_id)
            if not created:
                like_count.liked_num -= 1
                like_count.save()
                return JsonResponse({'code':1,'errmsg':'取消点赞成功','count':like_count.liked_num})
            else:
                return JsonResponse({'code':400,'errmsg':'取消点赞失败'})